﻿CREATE PROCEDURE [dbo].[Forum_Thread_Create]
	@userId UNIQUEIDENTIFIER,
	@sectionHashTag NVARCHAR(64),
	@title NVARCHAR(128),
	@value NVARCHAR(MAX)
AS
BEGIN

	DECLARE @sectionId SMALLINT

	SELECT @sectionId = [SectionId]
	FROM [dbo].[forum_Section]
	WHERE [HashTag] = @sectionHashTag

	IF @sectionId IS NULL
	BEGIN
		RAISERROR ('SectionNotFound',9,1)
		RETURN
	END

	DECLARE @threadId BIGINT

	SELECT @threadId = t.[ThreadId] 
	FROM [forum_Thread] AS t
	WHERE t.[SectionId] = @sectionId AND t.[CreatedBy] = @userId AND DATEDIFF(mi, t.[CreateDate], GETUTCDATE()) < 10 AND t.[Name] = @title --AND [Text] = @value

	IF @threadId IS NULL
	BEGIN
		BEGIN TRAN

		INSERT INTO [dbo].[forum_Thread]
							 ([SectionId]
							 ,[Name]
							 --,[Text]
							 ,[CreatedBy])
				 VALUES
							 (@sectionId
							 ,@title
							 --,@value
							 ,@userId)

		SET @threadId = SCOPE_IDENTITY()


		INSERT INTO [dbo].[forum_ThreadNote]
							 ([Text]
							 ,[ThreadId]
							 ,[Order]
							 ,[CreatedBy])
				 VALUES
							 (@value
							 ,@threadId
							 ,1
							 ,@userId)



		COMMIT TRAN
	END

	SELECT @threadId AS [ThreadId]
END